#include <iostream>
#include <string>
#include <string.h>

using namespace std;
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int st=0, len=1, lastlen=0, lastst=0;
        int length = s.size();
        if (length <= 1) {
            // then longest substring is s
            return length;
        }

        for (int i=1; i<s.size(); i++) {

            int prev = find(s, st, i);
            if (prev == -1) {
                len ++;
                if (len >= lastlen) {
                    lastlen = len;
                    lastst = st;
                }
            } else {
                len = i - prev;
                st = prev+1;
            }
        }
        if (lastlen > len) {
            len = lastlen;
            st = lastst;
        }
        string sub = s.substr(st, len);
        cout << sub << endl;
        return len;
    }

    int find(string &s, int st, int i) {

        for (int j=st; j<i; j++) {
            if (s[i] == s[j]) {
                return j;
            }
        }

        return -1;
    }

};


int main() {
    string s= "abcabcbb";
    Solution so;
    cout << so.lengthOfLongestSubstring(s) << endl;
    cout << so.lengthOfLongestSubstring("bbbbb") << endl;
    cout << so.lengthOfLongestSubstring("pwwkew") << endl;
    cout << so.lengthOfLongestSubstring("pwgwkew") << endl;
}

